# -*-coding:utf-8-*-
"""
@project: SM
@Time: 2024-08-01 19:53
@Author: Loneliness_Burial
@File: user_interface.py
@Motto: 深情不改必坠死海
@software: pycharm
@version: python 3.7
"""

from db import db_handler
from lib import common

"""
用户相关的接口
"""

logger = common.get_logger('user')


def register_interface(username, password, is_admin=False, balance=0):
    """
    注册接口
    :param username:用户名 str
    :param password:密码 str
    :param is_admin:是否管理员  boolean
    :param balance:初始余额 int
    :return:(boolean,str)
    """
    # 调用接口层的查询功能
    if db_handler.select_data(username, False):
        return False, '\n用户名已存在'
    user_data = {
        'username': username,
        'password': password,
        'balance': balance,  # 账户余额
        'shopping_cart': {},
        'flow': [],
        'is_admin': is_admin,
        'locked': False,  # 冻结账户
    }
    # 调用数据处理层
    db_handler.save(user_data)
    msg = f'用户: {username} 注册成功！'
    logger.info(msg)
    return True, msg


def login_interface(username, password):
    user_data = db_handler.select_data(username)
    if not user_data:
        return False, f'\n用户 {username} 不存在，请重新输入！', False
    if not password == user_data.get('password'):
        return False, '\n用户名或密码错误! ', False
    if user_data.get('locked'):
        return False, f'\n用户 {username} 已被冻结！', False
    msg = f'用户 {username} 登录成功！'
    logger.info(msg)
    return True, msg, user_data.get('is_admin')
